//
//  JCStatusPhotos.swift
//  SinaWeibo_18
//
//  Created by mac on 15/10/18.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit
import SDWebImage

//图片的最大数
private let PHOTO_MAX_COUNT = 9
//图片之间的间距
private let PHOTO_MARGIN : CGFloat = 10

class JCStatusPhotos: UIView {
    
    //定义图片列表模型 属性
    var pic_urls: [JCStatusPhotoInfo]?{
        didSet{
            //设置imageview
            setPicUrls()
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加9张图
        for _ in 0..<PHOTO_MAX_COUNT{
            let imageView = JCStatusPhotoImageView(frame: CGRectZero)
//            imageView.backgroundColor = randomColor()
           
            addSubview(imageView)
        }
    }
    private func setPicUrls(){
        
        //有多少张图片 显示多少imageview
        
        //隐藏所有 imageview
        for childView in subviews {
            childView.hidden = true
        }
        
        for i in 0..<pic_urls!.count {
            let childView = subviews[i] as! JCStatusPhotoImageView
            childView.hidden = false
            //得到每一个图片地址
            let info = pic_urls![i]
            //传入  图片地址
            childView.thumbnail_pic = info.thumbnail_pic!
        }
    }
    
    //设置子控件位置
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if pic_urls?.count == nil {
          return
        }
        
        let maxCol = 3
        //每个子控件的宽度
        let childViewWidth = (ScreenWidth - 4 * PHOTO_MARGIN) / CGFloat(maxCol)
        //如果有4张 图片   那么有俩列
        let tempCol = pic_urls!.count == 4 ? 2 : maxCol
        
        for i in 0..<pic_urls!.count{
            let childView = subviews[i]
            let col = i % tempCol
            let row = i / tempCol
            let childViewX = CGFloat(col) * (childViewWidth + PHOTO_MARGIN)
            let childViewY = CGFloat(row) * (childViewWidth + PHOTO_MARGIN)
            childView.frame = CGRectMake(childViewX, childViewY, childViewWidth, childViewWidth)
        }
    }
    // MARK: - 根据图片数量计算高度   总view
    class func countSize(count: Int) -> CGSize{
        
        let maxCol = 3
        
        //2->1 3->1 4->2
        let row = (count-1) / maxCol + 1
        let childViewW = (ScreenWidth - PHOTO_MARGIN * CGFloat(maxCol+1)) / CGFloat(maxCol)
        let viewW = ScreenWidth - CELL_CHILDVIEW_MARGIN * 2
        let viewH = CGFloat(row) * childViewW + CGFloat(row - 1) * PHOTO_MARGIN
        
        return CGSizeMake(viewW, viewH)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  
    
    

}
